package com.ipan.jfinal.simpleApi;

import java.nio.charset.Charset;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.ipan.kits.base.ExceptionUtil;
import com.ipan.kits.text.EncodeUtil;
import com.jfinal.kit.StrKit;

/**
 * 加密解密默认实现
 * 
 * AES/ECB/PKCS5Padding + BASE64
 * 
 * @author iPan
 * @date 2022-07-01
 */
public class SimpleApiEncryptImpl implements SimpleApiEncryptAble {
	
	private final Charset UTF_8 = Charset.forName("UTF-8");

	@Override
	public String encrypt(String input, String key) {
		if(StrKit.isBlank(input)) {
			return null;
		}
		byte[] crypted = null;
		try {
			SecretKeySpec skey = new SecretKeySpec(key.getBytes(UTF_8), "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, skey);
			crypted = cipher.doFinal(input.getBytes(UTF_8));
		} catch (Exception e) {
			ExceptionUtil.unchecked(e);
		}
		return EncodeUtil.encodeBase64(crypted);
	}

	@Override
	public String decrypt(String input, String key) {
		if(StrKit.isBlank(input)) {
			return null;
		}
		byte[] output = null;
		try {
			SecretKeySpec skey = new SecretKeySpec(key.getBytes(UTF_8), "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, skey);
			output = cipher.doFinal(EncodeUtil.decodeBase64(input));
		} catch (Exception e) {
			ExceptionUtil.unchecked(e);
		}
		return new String(output);
	}

}
